﻿/*****************************************************************
* Project: HFW Framework
*****************************************************************
* Developer: Hdhoan
* Date created: 11/2010
* Modified:
******************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HFW.Share;
using System.Collections;

namespace HFW.ADM
{
    public partial class frmLogin : BaseForm
    {
        public frmLogin()
        {

            InitializeComponent();
            backgroundWorkerND.DoWork += new DoWorkEventHandler(backgroundWorkerND_DoWork);
            backgroundWorkerND.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorkerND_RunWorkerCompleted);

            txtUserName.Text = "admin";
            txtPassword.Text = "123456";
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            using (var conn = new DataProvider.Connection())
            {
                var kq = conn.RunDynamicSQLScalar("ADM_CheckLogin", new object[] { txtUserName.Text.Trim(), txtPassword.Text.Trim() });
                if (kq.ToString()=="1")
                {
                    GetUserInfo(txtUserName.Text.Trim());
                    DialogResult = DialogResult.Yes;
                    this.Close();    
                    
                }
                else
                {
                    MessageBoxEX.Show("Người dùng hoặc mật khẩu không đúng", Applications.APPLICATION_TITLE_MESSAGEBOX, MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);
                    txtUserName.Focus();

                }
                
            }
        }
        private void frmLogin_Load(object sender, EventArgs e)
        {
            HdHoan.License lc = new HdHoan.License();
            HdHoan.ModifyRegistry mrg = new HdHoan.ModifyRegistry();
            string strLC="";
            try
            {
                strLC = mrg.Read("LICENSE").Trim();
            }
            catch (Exception)
            {

                strLC = "";
            }
            if (!lc.LicenseCheck(strLC, lc.GetHDDSerialNumber(null)))
            {

                tbHDD.Text = lc.GetHDDSerialNumber(null);
                pnLicense.Visible = true;
                pnlLoginInfo.Visible = false;
                pnlInitial.Visible = false;
            }
            else
            {
                pnLicense.Visible = false;
                pnlLoginInfo.Visible = false;
                pnlInitial.Visible = true;
                bwInitial();
            }

        }
        
        private bool CheckingServerState()
        {
            try
            {
                using (DataProvider.Connection conn = new DataProvider.Connection())
                {
                    conn.RunSQLNonQuery("select getdate()", CommandType.Text);
                    return true;
                }
            }
            catch (Exception)
            {

                return false;
            }

        }
        private bool CheckingClientDate()
        {
            try
            {
                DateTime svrTime = GetServerTime();
                DateTime localTime = svrTime.ToLocalTime();
                int intTimeZone = svrTime.Hour - localTime.Hour;
                PublishMessage("Client time : " + DateTime.Now.ToString());
                
                PublishMessage("Server time : " + svrTime.ToString());
                double dbDiffrentMinutes = svrTime.Subtract(DateTime.Now).TotalMinutes;
                if (dbDiffrentMinutes > 2 || dbDiffrentMinutes < -2)
                {
                    PublishMessage("Update client time...");
                    Global.SYSTEMTIME sysTime = new Global.SYSTEMTIME();
                    sysTime.wDay = (short)svrTime.Day;
                    sysTime.wDayOfWeek = (short)svrTime.DayOfWeek;
                    sysTime.wHour = (short)(svrTime.Hour + intTimeZone);
                    sysTime.wMilliseconds = (short)svrTime.Millisecond;
                    sysTime.wMinute = (short)(svrTime.Minute);
                    sysTime.wMonth = (short)svrTime.Month;
                    sysTime.wSecond = (short)svrTime.Second;
                    sysTime.wYear = (short)svrTime.Year;
                    if (!Global.SetSystemTime(ref sysTime))
                    {
                        RemoveAtList();
                        
                        PublishMessage("Update client time...\t\t\t\t\tError :"+Global.GetLastError().ToString());
                        PublishMessage("Automatic Update System Datetime does not run...\t\t\t\t\t");
                        PublishMessage("You must update your System Datetime to : "+svrTime.ToString());
                        return false;

                    }
                    else
                    {
                        RemoveAtList();
                        PublishMessage("Update client time...\t\t\t\t\tOK");
                        return true;
                    }
                }
                else
                {
                    RemoveAtList();
                    PublishMessage("Update client time...\t\t\t\t\tOK");
                    return true;
                }
            }
            catch (Exception)
            {
                PublishMessage("Update client time...\t\t\t\t\tError");
                return false;
            }
        }
        private DateTime GetServerTime()
        {
            object objDate = null;

            using (DataProvider.Connection conn = new DataProvider.Connection())
            {
                objDate = conn.RunSQLScalar("select getdate()", CommandType.Text);

                return DateTime.Parse(objDate.ToString());
            }
        }
        private void PublishMessage(string strAppendText)
        {
            try
            {
                lsbInitial.Items.Add(strAppendText);
            }
            catch { }
        }
        private void RemoveAtList()
        {
            try
            {
                lsbInitial.Items.RemoveAt(lsbInitial.Items.Count - 1);
            }
            catch (Exception)
            {
            }
        }

        private void uiButtonExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        #region Initial

        private void bwInitial()
        {
            try
            {
                while (backgroundWorkerND.IsBusy == true)
                {
                    Application.DoEvents();
                    System.Threading.Thread.Sleep(Global.DEFAULT_SLEEPTIME);
                }
                lock (this)
                {
                    backgroundWorkerND.RunWorkerAsync(Tasks.OTHERS);
                }
            }
            catch (Exception)
            {
            }
        }


        #region bw process

        private void backgroundWorkerND_DoWork(object sender, DoWorkEventArgs e)
        {
            string _strMsg = string.Empty;
            this.UseWaitCursor = true;
            backgroundWorkerND.ReportProgress(0);
            ArrayList arr_Argument_Of_bw = new ArrayList();
            arr_Argument_Of_bw.Add(e.Argument);
            try
            {
                switch ((Tasks)e.Argument)
                {
                    case Tasks.OTHERS:
                        {
                            bool bitSuccess = true;
                            _strMsg = "Initial global application variable...";
                            PublishMessage(_strMsg);
                            RemoveAtList();
                            _strMsg = "Initial global application variable...\t\t\t\tOK";
                            PublishMessage(_strMsg);
                            System.Threading.Thread.Sleep(Global.DEFAULT_SLEEPTIME);
                            _strMsg = "Checking server state...";
                            PublishMessage(_strMsg);
                            bitSuccess = CheckingServerState();
                            if (bitSuccess)
                            {
                                RemoveAtList();
                                _strMsg = "Checking server state...\t\t\t\t\tOK";
                                PublishMessage(_strMsg);
                                System.Threading.Thread.Sleep(Global.DEFAULT_SLEEPTIME);
                                _strMsg = "Checking client DateTime...";
                                PublishMessage(_strMsg);
                                bitSuccess = CheckingClientDate();
                                System.Threading.Thread.Sleep(Global.DEFAULT_SLEEPTIME);
                            }
                            else
                            {
                                RemoveAtList();
                                _strMsg = "Checking server state...\t\t\t\t\tError";
                                PublishMessage(_strMsg);
                            }

                            arr_Argument_Of_bw.Add(bitSuccess);
                            e.Result = arr_Argument_Of_bw;
                            break;
                        }
                    default:
                        {
                            break;
                        }
                }
            }
            catch (Exception)
            {
                this.UseWaitCursor = false;

            }
            finally
            {
                this.UseWaitCursor = false;
                e.Result = arr_Argument_Of_bw;
            }
        }

        private void backgroundWorkerND_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled == false)
            {
                ArrayList arr_Argument_Of_bw = (ArrayList)e.Result;
                try
                {
                    if (!e.Cancelled)
                    {
                        switch ((Tasks)arr_Argument_Of_bw[0])
                        {
                            case Tasks.OTHERS:
                                {
                                    if (arr_Argument_Of_bw[1].GetType().BaseType.Name.Contains("Exception"))
                                        throw (Exception)arr_Argument_Of_bw[1];
                                    else
                                    {
                                        bool result = (bool)arr_Argument_Of_bw[1];
                                        if (result == true)
                                        {
                                            this.Text = "Đăng nhập hệ thống";
                                            pnlLoginInfo.Visible = true;
                                            pnlInitial.Visible = false;
                                            this.txtUserName.Focus();
                                        }
                                        else
                                        {
                                            pnlLoginInfo.Visible = false;
                                            pnlInitial.Visible = true;
                                        }
                                    }
                                    break;
                                }
                            default:
                                {
                                    break;
                                }
                        }
                    }
                }
                catch (Exception)
                {
                    this.UseWaitCursor = false;
                }
                finally
                {
                    this.UseWaitCursor = false;
                }
            }
        }
        #endregion

        private void btExit2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }





        #endregion

        private void btDangKy_Click(object sender, EventArgs e)
        {
            HdHoan.License lcc = new HdHoan.License();
            HdHoan.ModifyRegistry mrgg = new HdHoan.ModifyRegistry();
            if (lcc.LicenseCheck(tbLicense.Text, tbHDD.Text))
            {
                try
                {
                    mrgg.Write("LICENSE", tbLicense.Text);
                    MessageBoxEX.Show("Đăng ký bản quyền thành công.");
                    Application.Exit();
                }
                catch (Exception)
                {
                    MessageBoxEX.Show("Không thể lưu bản quyền.");
                }
               
            }
            else
            {
                MessageBoxEX.Show("Mã đăng ký không đúng");
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://192.168.1.216:2412/default.aspx?HDD="+tbHDD.Text);
        }
        private void GetUserInfo(string UserID)
        {
            DataSet dss = new DataSet();
            try
            {
                using (DataProvider.Connection conn = new DataProvider.Connection())
                {
                    dss = conn.RunDynamicSQLQuery("ADM_GetUserInfo", new object[] { UserID });
                }
                Applications.CURRENT_USER_ID=dss.Tables[0].Rows[0]["UserGroupID"].ToString();
                Applications.CURRENT_USER_NAME = dss.Tables[0].Rows[0]["UserGroupName"].ToString();

            }
            catch (Exception)
            {
            }
        }
    }
}
